using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace MicroFractal.iTunesBrowser.Core.Helper
{
    public static class ITunesHelper
    {
        public static int BytesToInt(byte[] b)
        {
            int result = 0;

            for (int i = 0; i < b.Length; i++)
            {
                result += b[i] << (i * 8);
            }
            return result;
        }

        public static MemoryStream GetMemoryStream(MemoryStream originalStream, int offset)
        {
            originalStream.Position = offset;

            MemoryStream stream = new MemoryStream();
            byte[] buffer = new byte[1024];

            int count = originalStream.Read(buffer, 0, buffer.Length);
            while (count > 0)
            {
            stream.Write(buffer, 0, count);
                count = originalStream.Read(buffer, 0, buffer.Length);
            }

            originalStream.Position = 0;
            stream.Position = 0;

            return stream;
        }

        public static MemoryStream GetMemoryStream(MemoryStream originalStream, int offset, int length)
        {
            //originalStream.Position = 0;
            //byte[] b = new byte[4];
            //originalStream.Position = lenghtPosition;
            //originalStream.Read(b, 0, 4);
            //originalStream.Position = ITunesHelper.BytesToInt(b);
            originalStream.Position = offset;

            MemoryStream stream = new MemoryStream();
            byte[] buffer = new byte[length];

            int count = originalStream.Read(buffer, 0, buffer.Length);
            //while (count > 0)
            //{
            stream.Write(buffer, 0, count);
            //    count = originalStream.Read(buffer, 0, buffer.Length);
            //}

            originalStream.Position = 0;
            stream.Position = 0;

            return stream;
        }

        public static int BytesToInt(Stream s, int offset, int length)
        {
            long pos = s.Position;
            byte[] b = new byte[length];
            s.Position = offset;
            s.Read(b, 0, length);
            s.Position = pos;
            return BytesToInt(b);
        }

        public static string BytesToString(Stream s, int offset, int length, Encoding encoder)
        {
            byte[] b = new byte[length];
            long pos = s.Position;
            s.Position = offset;
            s.Read(b, 0, length);
            s.Position = pos;
            return encoder.GetString(b);
        }

    }
}
